<template>
  <div>
    <bread-crumb
      class="bread-crumb-padding"
      :list="breadCrumb"
      :user="true"
    ></bread-crumb>
    <div class="user-main-box">
      <user-tab-list
        :list="tablist"
        :returnButton="true"
        backUrl="/user/account"
      ></user-tab-list>
      <div class="form-input-area">
        <div class="box-area" style="position: relative">
          <Spin :withIcon="true" v-if="loading"></Spin>
          <div class="line-item">
            <span class="name">可用金额</span>
            <span class="f-14 c-o"
              >{{ $store.state.user.balance }}<span class="c-d2">元</span></span
            >
          </div>
          <div class="line-item flx-row-s-c">
            <span class="name">充值金额</span>
            <input
              type="text"
              v-model="money"
              placeholder="请输入"
              class="bankNumber"
              style="width: 100px; margin-right: 10px"
              @input="inputNumberChange"
              @paste="paste"
            />
            <span class="f-14 c-black"
              >元<span style="margin-left: 12px">充值最小金额1元 </span></span
            >
          </div>
          <div class="line-item flx-row-s-s">
            <span class="name">充值方式</span>
            <div
              class="pay-method-box"
              :class="[item.icon, paySelect == index ? 'active' : '']"
              v-for="(item, index) in payMethods"
              :key="index"
              @click="paySelect = index"
            >
              {{ item.name }}
            </div>
          </div>
          <div
            class="user-strong-button submit-button-size"
            @click="createRecharge"
          >
            确认充值
          </div>
        </div>
      </div>
    </div>

<!--    <div class="user-main-box pub-m-t-20">-->
<!--      <div class="b-b-d"><div class="box-title">银行汇款（对公）</div></div>-->
<!--      <div class="flx-row-s-s" style="padding: 30px 0">-->
<!--        <img-->
<!--          style="width: 358px"-->
<!--          :src="require('_a/images/bank-logo@2x.png')"-->
<!--        />-->
<!--        <div class="flx-col pub-m-l-36">-->
<!--          <span class="c-black f-14" style="margin-bottom: 10px"-->
<!--            >公司名称：北京荟米科技有限公司</span-->
<!--          >-->
<!--          <span class="c-black f-14" style="margin-bottom: 10px"-->
<!--            >银行账号：41021500040024949</span-->
<!--          >-->
<!--          <span class="c-black f-14" style="margin-bottom: 10px"-->
<!--            >开户银行：中国农业银行深圳坪洲支行</span-->
<!--          >-->
<!--          <span class="c-o f-14"-->
<!--            >汇款成功后请将汇款凭证及充值ID发送至kf@190.vip，等待客服审核处理。</span-->
<!--          >-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
    <pay-code-modal
      type="1"
      :show.sync="wechatPayModalShow"
      :codeUrl="wechatPayCode"
    ></pay-code-modal>
    <!-- <pay-code-modal
      type="2"
      :show.sync="zhifubaoPayModalShow"
      :codeUrl="zhifubaoPayCode"
    ></pay-code-modal> -->
    <payZhifubaoModal
      :show.sync="zhifubaoPayModalShow"
      :codeUrl="zhifubaoPayCode"
    ></payZhifubaoModal>
  </div>
</template>

<script>
import { createRecharge } from "@/api/user";
const webScoketUrl =
  process.env.NODE_ENV === "development"
    ? config2.webScoketUrl.dev
    : config2.webScoketUrl.pro;
import { mapActions } from "vuex";
export default {
  name: "VipAccountRecharge",
  components: {
    payCodeModal: () => import("_c/modal/payCodeModal/payCodeModal.vue"),
    payZhifubaoModal: () => import("_c/modal/payCodeModal/payZhifubaoModal.vue"),
  },
  data() {
    return {
      loading: false,
      breadCrumb: [{name: "管理中心"},{ name: "财务管理" }, { name: "账户信息" }],
      tablist: [
        {
          name: "在线充值",
          to: "/user/recharge",
        },
      ],
      payMethods: [
        {
          name: "微信",
          icon: "p-i-2",
          id: "2",
        },
        {
          name: "支付宝",
          icon: "p-i-1",
          id: "1",
        },
        // {
        //   name: "银联",
        //   icon: "p-i-3",
        //   id: "3",
        // },
      ],
      money: "",
      paySelect: -1,
      //弹出框
      wechatPayModalShow: false,
      wechatPayCode: "",
      zhifubaoPayModalShow: false,
      zhifubaoPayCode: "",
      orderNo: "",
    };
  },
  methods: {
    ...mapActions(["getAmountData"]),
    // 数值改变
    inputNumberChange() {
      if (this.money == null) return;
      var money = this.money.replace(/[^\d.]/g, "");
      if (/^(\.)$/.test(money)) {
        money = "0.";
      }
      if (/^(\d?)+(\.\d{0,2})?$/.test(money)) {
        //正则验证，提现金额小数点后不能大于两位数字
        if (/^(0[0]*)$/.test(money)) {
          this.money = money.replace(/^(0*)/g, "0");
        } else if (/^(0[1-9]*)$/.test(money)) {
          this.money = money.replace(/^(0*)/g, "");
        } else {
          this.money = money;
        }
      } else {
        this.money = money.substring(0, money.length - 1);
      }
    },
    // 拦截贴贴事件
    paste(e) {
      e.preventDefault();
      return "";
    },
    // 创建充值
    async createRecharge() {
      if (!this.money) {
        this.$Message.warning("请输入充值金额！");
        return;
      }
      if (this.money < 1) {
        this.$Message.warning("充值最小金额1元！");
        return;
      }
      if (this.paySelect == -1) {
        this.$Message.warning("请选择充值方式！");
        return;
      }
      let data = {
        amount: this.money,
        type: this.paySelect,
      };
      if(this.paySelect == 0){
        data.source = 0
      }else if(this.paySelect == 1){
        data.source = 2
      }
      this.loading = true;
      let res = await createRecharge(data);
      if (res.code == 200) {
        if (this.paySelect == 0) {
          this.wechatPayCode = res.data.url;
          this.orderNo = res.data.orderNo;
          this.wechatPayModalShow = true;
        } else if (this.paySelect == 1) {
          this.zhifubaoPayCode = res.data.url;
          this.orderNo = res.data.orderNo;
          this.zhifubaoPayModalShow = true;
        }
        this.startSocket();
      }
      this.loading = false;
    },
    // webScoket发送消息
    sendMessage(txt) {
      this.webSocket.send(txt);
    },
    // webScoket异常重连
    resetConnect() {
      this.connectCount = this.connectCount || 0;
      if (!this.webSocketInterval) {
        this.webSocketResetInterval = setInterval(() => {
          this.connectCount += 1;
          if (this.connectCount <= 5) {
            this.startSocket();
            this.webSocketResetInterval &&
              clearInterval(this.webSocketResetInterval);
          }
        }, 1000);
      }
    },
    // 开启webScoket
    startSocket() {
      this.messageTotal = 0;
      this.webSocket = new WebSocket(
        `${webScoketUrl}/web/webSocket/pay/${this.orderNo}/${this.$token.get().accessToken}`
      );
      // 接收消息事件
      this.webSocket.onmessage = (e) => {
        if (e.data === "open:suc") {
          this.sendMessage("start");
          this.heartInterval = setInterval(() => {
            if (this.messageTotal === 10) {
              this.sendMessage("heart");
              this.messageTotal = 0;
            }
            this.messageTotal += 1;
          }, 1000);
        }
        if (e.data.indexOf("msg:") != -1) {
          let message = e.data.split("msg:")[1];
          this.messageTotal = 0;
          let info = JSON.parse(message);
          if (info != null) {
            if (info.result == "1") {
              this.clearSocket();
              if (this.paySelect == 0) {
                this.wechatPayModalShow = false;
              } else if (this.paySelect == 1) {
                this.zhifubaoPayModalShow = false;
              }
              this.$Message.success("充值成功！");
              this.money = "";
              this.getAmountData();
            } else if (info.result == "2" || info.result == "3") {
              this.clearSocket();
              if (this.paySelect == 0) {
                this.wechatPayModalShow = false;
              } else if (this.paySelect == 1) {
                this.zhifubaoPayModalShow = false;
              }
              this.$Message.warning("充值失败！");
              this.money = "";
              this.getAmountData();
            }
          }
        }
        if (e.data.indexOf("rec:stop") != -1) {
          this.webSocket.close();
        }
      };
      // 关闭事件
      // this.webSocket.onclose = () => {
      //   this.resetConnect();
      // };
      // 连接失败事件
      this.webSocket.onerror = () => {
        this.resetConnect();
      };
    },
    // 清空socket
    clearSocket() {
      if (this.webSocket) {
        this.sendMessage("stop");
        this.heartInterval && clearInterval(this.heartInterval);
        this.webSocketResetInterval &&
          clearInterval(this.webSocketResetInterval);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box-area {
  width: 800px;
  padding: 20px 30px 30px;
  border-radius: 5px;

  .line-item {
    margin-bottom: 20px;
  }
  .name {
    text-align: right;
    margin-right: 25px;
    font-size: 14px;
    color: #000;

    &::after {
      content: ":";
    }
  }
  .pay-method-box {
    @include size(200px, 75px);
    border: 1px solid #dcdee2;
    // padding: 12px 13px 12px 53px;
    line-height: 75px;
    text-align: center;
    padding-left: 40px;
    border-radius: 5px;
    transition: border-color 0.3s, color 0.3s;
    font-size: 16px;
    color: #000;
    font-weight: 600;
    cursor: pointer;
    margin-right: 20px;
    &:hover,
    &.active {
      border-color: #F68A0C;
      color: #F68A0C;
    }

    &.p-i-1 {
      @include bg-setting("p-i-1", 54px, 16px center);
    }
    &.p-i-2 {
      @include bg-setting("p-i-2", 52px, 20px center);
    }
    // &.p-i-3 {
    //   @include bg-setting("p-i-3", 31px 19px, 13px center);
    // }
  }
  .submit-button-size {
    @include size(118px, 41px);
    @include btn-s(null, 41px, 5px);
    margin-left: 85px;
  }

  img {
    width: 195px;
    margin-top: 20px;
    margin-right: 38px;
  }
}

.box-title {
  font-size: 16px;
  color: #000;
  font-weight: 600;
  padding-bottom: 20px;
  width: max-content;
}
.bankNumber {
  border: 1px solid #dcdee2;
  border-radius: 4px;
  width: 100%;
  height: 32px;
  line-height: 1.5;
  padding: 4px 7px;
  font-size: 14px;
  transition: border 0.2s ease-in-out, background 0.2s ease-in-out,
    box-shadow 0.2s ease-in-out;
  background-color: #fff;
  color: #20213c;
}
.bankNumber::placeholder {
  color: #c5c8ce;
}
.bankNumber:focus,
.bankNumber:hover {
  border-color: #F68A0C !important;
  box-shadow: none !important;
}
.form-input-area {
  padding: 30px 20px 60px !important;
}
</style>
